﻿using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Brush = System.Drawing.Brush;
using Color = System.Drawing.Color;
using Pen = System.Drawing.Pen;
using Point = System.Drawing.Point;
using Rectangle = System.Drawing.Rectangle;

namespace classTest
{
    /// <summary>
    /// HistogramWindow.xaml 的交互逻辑
    /// </summary>
    public partial class HistogramWindow : Window
    {

        LayerCollection layers;
        Dictionary<string, int[]> values = new Dictionary<string, int[]>();
        public HistogramWindow(LayerCollection layers1)
        {
            InitializeComponent();
            layers = layers1;

            FeatureLayer featureLayer = null;
            for (var i = layers.Count - 1; i >= 0; i--)
            {
                if (layers[i].Name == "StudentDormitory")
                {
                    featureLayer = layers[i] as FeatureLayer;
                }
            }
            if (featureLayer == null)
            {
                MessageBox.Show("没有找到StudentDormitory图层");
                return;
            }

            Initialize(featureLayer);
        }
        private void Drawing()
        {
            //生成图形
            Bitmap bitmap = new Bitmap(600, 500);
            bitmap.MakeTransparent();
            Graphics g = Graphics.FromImage(bitmap);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            //标题
            Font f = new Font("宋体", 12, System.Drawing.FontStyle.Regular);
            Pen p = new Pen(Color.Blue);
            g.DrawString("华农各校区男女人数专题图", f, (new Pen(Color.Black)).Brush, 150, 20);

            //画表格
            for (int i = 0; i <= 10; i++)
            {
                g.DrawLine(p, 50, 90 + 31 * i, 590, 90 + 31 * i);
            }
            for (int i = 1; i < 13; i++)
            {
                g.DrawLine(p, 50 + 42 * i, 70, 50 + 42 * i, 400);
            }

            Pen MyPen = new Pen(Color.Blue, 2);
            Point p1 = new Point(50, 70);
            Point p2 = new Point(50, 400);
            Point p3 = new Point(50, 400);
            Point p4 = new Point(590, 400);
            g.DrawLine(MyPen, p1, p2);
            g.DrawLine(MyPen, p3, p4);


            //蓝色图形部分
            Pen drawPen = new Pen(Color.SkyBlue, 1);
            SolidBrush mybrush = new SolidBrush(Color.SkyBlue);
            //粉色图形部分
            Pen drawPen2 = new Pen(Color.LightPink, 1);
            SolidBrush brush = new SolidBrush(Color.LightPink);
            //图上的文字部分
            Font font2 = new Font("宋体", 8, System.Drawing.FontStyle.Regular);
            //蓝色数
            Pen pen2 = new Pen(Color.SkyBlue);
            //粉色数
            Pen pen3 = new Pen(Color.LightPink);
            for (int i = 0; i<values.Count; i++)
            {
                int boy = Convert.ToInt16((float)values.Values.ElementAt(i)[0]/1000*31);
                //红色图形部分
                g.DrawRectangle(drawPen, 50 + 42 * i*2 + 21, 400  - boy, 21, boy);
                g.FillRectangle(mybrush, 50 + 42 * i*2 + 21, 400 - boy, 21, boy);

                int girl = Convert.ToInt16((float)values.Values.ElementAt(i)[1] / 1000 * 31);

                //Console.WriteLine($"男：{boy},女{girl}");
                //绿色图形部分
                g.DrawRectangle(drawPen2, 50 + 42 * i * 2 + 42, 400 - girl, 21, girl);
                g.FillRectangle(brush, 50 + 42 * i * 2 + 42, 400 - girl, 21, girl);

                //图上的文字部分
                g.DrawString(values.Keys.ElementAt(i), font2, p.Brush, 50 + 21 +42*i*2, 405);

                //红色数
                g.DrawString(values.Values.ElementAt(i)[0].ToString(), font2, pen2.Brush, 50 + 42 * i * 2 + 21, 400- boy-20);

                //绿色数
                g.DrawString(values.Values.ElementAt(i)[1].ToString(), font2, pen3.Brush, 50 + 42 * i * 2 + 42, 400 - girl-20);
            }

            //图上数字部分
            g.DrawString("1000", font2, p.Brush, 5, 400 - 35);
            g.DrawString("2000", font2, p.Brush, 5, 400 - 35 * 2);
            g.DrawString("3000", font2, p.Brush, 5, 400 - 34 * 3);
            g.DrawString("4000", font2, p.Brush, 5, 400 - 33 * 4);
            g.DrawString("5000", font2, p.Brush, 5, 400 - 33 * 5);
            g.DrawString("6000", font2, p.Brush, 5, 400 - 32 * 6);
            g.DrawString("7000", font2, p.Brush, 5, 400 - 32 * 7);
            g.DrawString("8000", font2, p.Brush, 5, 400 - 32 * 8);
            g.DrawString("9000", font2, p.Brush, 5, 400 - 32 * 9);
            g.DrawString("10000", font2, p.Brush, 5, 400 - 32 * 10);

            //最下面的矩形框
            g.DrawRectangle(p, 50 + 42 * 2 + 30, 430, 42 * 7, 31 * 2);

            g.DrawRectangle(drawPen, 50 + 42 * 5, 440, 21, 10);
            g.FillRectangle(mybrush, 50 + 42 * 5, 440, 21, 10);
            g.DrawString("男生人数", font2, pen2.Brush, 50 + 42 * 6, 440);

            g.DrawRectangle(drawPen2, 50 + 42 * 5, 470, 21, 10);
            g.FillRectangle(brush, 50 + 42 * 5, 470, 21, 10);
            g.DrawString("女生人数", font2, pen3.Brush, 50 + 42 * 6, 470);

            p.Dispose();
            MyPen.Dispose();
            drawPen.Dispose();
            drawPen2.Dispose();
            pen2.Dispose();
            pen3.Dispose();
            g.Dispose();

            imageBox.Source = ChangeBitmapToImageSource(bitmap);
        }

        private async void Initialize(FeatureLayer featureLayer)
        {
            List<string> dormitoryArea = new List<string>();

            FeatureQueryResult result = await featureLayer.FeatureTable.QueryFeaturesAsync(new QueryParameters());//构建查询参数对象在表对象上进行查询
            if (result == null) return;
            foreach (Feature ft in result)//遍历查询结果
            {
                string strValue = null;
                try
                {
                    strValue = ft.GetAttributeValue("宿舍区").ToString();//取得当前字段值
                }
                catch
                {
                    return;
                }
                if (!dormitoryArea.Contains(strValue))//检查该值是否已存在
                {
                    dormitoryArea.Add(strValue);//加入字段值列表框
                }
            }
            for (int i = dormitoryArea.Count - 1; i >= 0; i--)
            {
                string name = dormitoryArea[i];
                QueryParameters qParams = new QueryParameters();//创建查询参数对象
                                                                // 求女生总数
                qParams.WhereClause = $"宿舍区 = '{name}' AND 宿舍类型 = '女'";//获取文本框中的字符串作为查询参数对象的where子句
                FeatureQueryResult result1 = await featureLayer.FeatureTable.QueryFeaturesAsync(qParams);//在表上进行查询
                int peopleGirl = 0;
                foreach (Feature f in result1)
                {
                    peopleGirl += Convert.ToInt32(f.GetAttributeValue("已住人数"));//取得当前字段值
                }
                // 求男生总数
                qParams.WhereClause = $"宿舍区 = '{name}' AND 宿舍类型 = '男'";//获取文本框中的字符串作为查询参数对象的where子句
                FeatureQueryResult result2 = await featureLayer.FeatureTable.QueryFeaturesAsync(qParams);//在表上进行查询
                int peopleBoy = 0;
                foreach (Feature f in result2)
                {
                    peopleBoy += Convert.ToInt32(f.GetAttributeValue("已住人数"));//取得当前字段值
                }
                values.Add(name,new int[] { peopleBoy, peopleGirl });
                Console.WriteLine($"宿舍区：{name}，男：{peopleBoy}，女：{peopleGirl}");

            }

            Drawing();
        }

        // Bitmap 与ImageSource之间的转换
        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);
        public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
        {
            IntPtr hBitmap = bitmap.GetHbitmap();
            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
            if (!DeleteObject(hBitmap))//记得要进行内存释放。否则会有内存不足的报错。
            {
                throw new System.ComponentModel.Win32Exception();
            }
            return wpfBitmap;
        }
    }
}
